package com.pocketmenu.business;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import com.google.android.maps.GeoPoint;
import com.pocketmenu.persistence.SQLiteHelper;
import com.pocketmenu.ui.R;

import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class RestaurantCursorAdapter extends SimpleCursorAdapter {

	private int layout;
	private OnTouchListener listener;	
	
	public RestaurantCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, OnTouchListener listener) {
		super(context, layout, c, from, to);
		this.layout = layout;
		this.listener = listener;
	}
	
	@Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        Cursor c = getCursor();

        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);        
        v.setOnTouchListener(listener);        
        
        return bindValues(v, context, c);
    }
	
	private View bindValues(View v, Context context, Cursor c)
	{
		int descriptionIndex = c.getColumnIndex(SQLiteHelper.COLUMN_RESTAURANT_DESCRIPTION);
    	int nameIndex = c.getColumnIndex(SQLiteHelper.COLUMN_RESTAURANT_NAME);
    	int latitudIndex = c.getColumnIndex(SQLiteHelper.COLUMN_RESTAURANT_LATITUD);
    	int longitudIndex = c.getColumnIndex(SQLiteHelper.COLUMN_RESTAURANT_LONGITUD);
    	int distanceIndex = c.getColumnIndex(SQLiteHelper.COLUMN_RESTAURANT_DISTANCE);
    	
        String description = c.getString(descriptionIndex);
        String name = c.getString(nameIndex);
        String latitud = c.getString(latitudIndex);
        String longitud = c.getString(longitudIndex);
        int distance = c.getInt(distanceIndex);
        
        TextView tvDescriptionTemp = (TextView) v.findViewById(R.id.tvRestaurantDescription);
        if (tvDescriptionTemp != null) {
        	if(description.length() > 40)
        		tvDescriptionTemp.setText(description.substring(0, 36) + " ...");
        	else
        		tvDescriptionTemp.setText(description);
        }

        TextView tvNameTemp = (TextView) v.findViewById(R.id.tvRestaurantName);
        if (tvNameTemp != null) {
        	tvNameTemp.setText(name);
        }
        
        TextView tvDistance = (TextView) v.findViewById(R.id.tvRestaurantDistance);
        if (tvDistance != null) {
        	if(distance != -1)
	        	tvDistance.setText(distance + " m");        	
        	else
        		tvDistance.setVisibility(View.GONE);
        }
        
        return v;
	}
	
    @Override
    public void bindView(View v, Context context, Cursor c) {
    	
    	bindValues(v, context, c);
    }           
	
}
